package com.mingmen.canting.caigourenyuan;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.canting.R;
import com.mingmen.canting.activity.LoginActivity;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.defineview.ParentRecyclerView;
import com.mingmen.canting.fragment.BaseFragment;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.model.ShoppingCartModel;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.util.ToolList;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

@SuppressLint("ValidFragment")
public class CaiGouRenDaiListragment extends BaseFragment {

    @BindView(R.id.recyclerview)
    ParentRecyclerView mRecyclerview;

    Unbinder unbinder;

    private String mTitle;


    CaiGouRenDaiCaiAdapter chuShiDingDanAdapter;

    String token;


    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;
    @BindView(R.id.text_time)
    TextView text_time;
    LinearLayoutManager linearLayoutManager;
    List<ShoppingCartModel.DataBean.SupDataListBean> dataBeanList = new ArrayList<>();
    private MyBroadcastReceiver myBroadcastReceiver;
    String childPosition;
    private int result_fangqi = 200;
    String applyDetailId;
    @BindView(R.id.btn_submit)
    Button btn_submit;

    List<String> cancelFlag = new ArrayList<>();

    List<String> supplierNameList = new ArrayList<>();
    @BindView(R.id.text_total)
    TextView text_total;

    private class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //系统服务类
            String pos = intent.getStringExtra("pos");
            Log.d("pospospos", pos);
            childPosition = intent.getStringExtra("position");

        }
    }

    private IntentFilter intentFilter;

    public static CaiGouRenDaiListragment getInstance(String title) {
        CaiGouRenDaiListragment sf = new CaiGouRenDaiListragment();
        sf.mTitle = title;
        return sf;
    }


    @Override
    public View initView() {
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.fr_caigoudai, null);
        TextView card_title_tv = (TextView) v.findViewById(R.id.card_title_tv);
        card_title_tv.setText(mTitle);
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this, v);
        registerBroad();
        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerview.setLayoutManager(linearLayoutManager);
        chuShiDingDanAdapter = new CaiGouRenDaiCaiAdapter(getActivity(), dataBeanList);
        mRecyclerview.setAdapter(chuShiDingDanAdapter);

        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.custom_divider));
        mRecyclerview.addItemDecoration(divider);


        TextView text_detail = v.findViewById(R.id.text_detail);
        text_detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SelectGongYingActivity.class);
                intent.putExtra("detailIds", "239392");
                intent.putExtra("position", "666");
//                startActivityForResult(intent, result_shouhuo);
            }
        });
        getData();
        return v;
    }

    @Override
    public void initData() {

    }


    @Override
    public void onResume() {
        super.onResume();
    }

    List<String> detailIds = new ArrayList<>();
    List<String> applyIds = new ArrayList<>();
    List<String> ids = new ArrayList<>();
    List<String> commpanyNames = new ArrayList<>();
    List<String> allIds = new ArrayList<>();


    public void getData() {
        //        2
//        1
        chuShiDingDanAdapter = new CaiGouRenDaiCaiAdapter(getActivity(), dataBeanList);
        mRecyclerview.setAdapter(chuShiDingDanAdapter);
        HttpResponse.getShoppingCart(token, "2", "", new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("CaiGouRenyuan", s);
                if (dataBeanList.size() > 0) {
                    dataBeanList.clear();
                }
                if (supplierNameList.size() > 0) {
                    supplierNameList.clear();
                }
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    ShoppingCartModel shoppingCartModel = new ShoppingCartModel();
                    shoppingCartModel = GsonUtil.GsonToBean(s, ShoppingCartModel.class);
                    dataBeanList.addAll(shoppingCartModel.getData().get(0).getSupDataList());
                    text_time.setText(shoppingCartModel.getData().get(0).getLimitedDate());
                    text_total.setText("总价: " + shoppingCartModel.getData().get(0).getTotal() + "元");
                    if (detailIds.isEmpty()) {
                    } else {
                        detailIds.clear();
                        allIds.clear();
                    }

                    if (cancelFlag.size() > 0) {
                        cancelFlag.clear();
                    }
                    if (supplierNameList.size() > 0) {
                        supplierNameList.clear();
                        allIds.clear();
                    }

                    for (int i = 0; i < shoppingCartModel.getData().get(0).getSupDataList().size(); i++) {
                        for (int j = 0; j < shoppingCartModel.getData().get(0).getSupDataList().get(i).getDetails().size(); j++) {
                            cancelFlag.add(shoppingCartModel.getData().get(0).getSupDataList().get(i).getDetails().get(j).getCancelFlag());
                            supplierNameList.add(shoppingCartModel.getData().get(0).getSupDataList().get(i).getDetails().get(j).getSupplierName());
                            allIds.add(shoppingCartModel.getData().get(0).getSupDataList().get(i).getDetails().get(j).getCommodityId());
                        }
                    }

                    Log.d("DETAILIDS", detailIds.toString());

                    chuShiDingDanAdapter.setDataList(dataBeanList);
                    chuShiDingDanAdapter.notifyDataSetChanged();
                } else if (baseBean.getCode() == 401) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    getActivity().finish();
                } else {
                    Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                }

            }
        });
        List<String> myReceiveList = new ArrayList<>();
        chuShiDingDanAdapter.setOnitemClickLintener(new CaiGouRenDaiCaiAdapter.OnitemClick() {
            @Override
            public void onItemClick(View view, int parentPosition, int position, List<ShoppingCartModel.DataBean.SupDataListBean.DetailsBean> mList, List<ShoppingCartModel.DataBean.SupDataListBean> mNewList) {
                Intent intent;
                int allSize = mList.size() + mNewList.size();
                switch (view.getId()) {
                    case R.id.text_fangqi:
                        if (dataBeanList.size() > 0) {
                            dataBeanList.clear();
                        }
                        if (mList.get(position).getCancelFlag().equals("1")) {
                            HttpResponse.doShoppingCartCancel(token, mList.get(position).getApplyDetailId(), reason, new StringCallback(getActivity()) {
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    Log.d("CaiGouRenDaiList", s);
                                    BaseBean baseBean = new BaseBean();
                                    baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                                    Toast.makeText(mContext, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                                    getData();
                                }
                            });
                        } else {
                            Log.d("parentPositionParentPosition", "parentPosition" + mList.get(position).getApplyId());
                            applyDetailId = mList.get(position).getApplyDetailId();

                            intent = new Intent(getActivity(), FilterFangQiActivity.class);
                            startActivityForResult(intent, result_fangqi);

                        }

                        break;

                    case R.id.layout_selectshouhuo:
                        intent = new Intent(getActivity(), ShouhuoListActivity.class);
//                        intent.putExtra("supplierId", mNewList.get(0).getDetails().get(0).getSupplierId());
//                        startActivityForResult(intent, result_shouhuo);
                        intent.putExtra("supplierId", "0");
                        startActivity(intent);
                        break;
                    case R.id.lable_selectcanting:
                        String mYdetailIds = MyStringUtils.returnStringBuffer(ids);
                        Log.d("commodityIdscommodityIds", mYdetailIds);
                        String applyId_s = MyStringUtils.returnStringBuffer(applyIds);
                        String commpanyName_s = MyStringUtils.returnStringBuffer(commpanyNames);

                        Log.d("commpanyNamescommpanyNames", commpanyNames.toString());
                        Log.d("idsids", ids.toString());
                        if (TextUtils.isEmpty(ids.toString())) {
                            Toast.makeText(mContext, "请选择商品", Toast.LENGTH_SHORT).show();
                        } else if (ids.size() == 0) {
                            Toast.makeText(mContext, "请选择商品", Toast.LENGTH_SHORT).show();
                        } else {
                            ToolList.removeDuplicateWithOrder(commpanyNames);
                            ToolList.removeDuplicateWithOrder(applyIds);
                            ToolList.removeDuplicateWithOrder(detailIds);
                            ToolList.removeDuplicateWithOrder(myReceiveList);
                            intent = new Intent(getActivity(), SelectGongYingActivity.class);
                            intent.putExtra("detailIds", mYdetailIds);
                            intent.putExtra("position", position + "");
                            intent.putExtra("applyId_s", applyId_s);
                            intent.putExtra("commpanyNames", commpanyName_s);
                            startActivityForResult(intent, result_shouhuo);
                        }
                        break;
                    case R.id.checkbox_groupitem:
                        Log.d("mListmList", mList.size() + "");
                        Log.d("mNewList", mNewList.size() + "");
                        Log.d("parentPosition", parentPosition + "");
                        Log.d("Position", position + "");

                        if (mNewList.get(parentPosition).isSelect() == true) {
                            for (int i = 0; i < mNewList.get(parentPosition).getDetails().size(); i++) {
                                Log.d("commodityName", mList.get(i).getCommodityName());
                                Log.d("commodityId", mList.get(i).getCommodityId());
                                Log.d("applyDetailId", mList.get(i).getApplyDetailId());
                                myReceiveList.add(mList.get(i).getCommodityName());
                                applyIds.add(mList.get(i).getCommodityId());
                                detailIds.add(mList.get(i).getApplyDetailId());
                                commpanyNames.add(mList.get(i).getCommodityName());
                                ids.add(mList.get(i).getApplyDetailId());
                                mNewList.get(parentPosition).getDetails().get(i).setSelect(true);
                            }

                            Log.d("idsidsidsids", ids.size() + "");
                            mNewList.get(parentPosition).setSelect(true);
                            chuShiDingDanAdapter.notifyDataSetChanged();
                            ToolList.removeDuplicateWithOrder(commpanyNames);
                            ToolList.removeDuplicateWithOrder(applyIds);
                            ToolList.removeDuplicateWithOrder(detailIds);
                            ToolList.removeDuplicateWithOrder(myReceiveList);
                            ToolList.removeDuplicateWithOrder(ids);
                        } else {
                            for (int i = 0; i < mNewList.get(parentPosition).getDetails().size(); i++) {
                                mNewList.get(parentPosition).getDetails().get(i).setSelect(false);
                            }
                            mNewList.get(parentPosition).setSelect(false);
                            myReceiveList.clear();
                            applyIds.clear();
                            detailIds.clear();
                            commpanyNames.clear();
                            ids.clear();
                            chuShiDingDanAdapter.notifyDataSetChanged();
                            Log.d("idsidsidsids", ids.size() + "");
                        }

                        Log.d("myReceiveListmyReceiveList", myReceiveList.toString() + "");

                        break;

                    case R.id.checkbox:


                        Log.d("mListmList", mList.size() + "");
                        Log.d("mNewList", mNewList.size() + "");
                        Log.d("parentPosition", parentPosition + "");
                        Log.d("Position", position + "");
                        Log.d("allSize", allSize + "");
                        for (int i = 0; i < mList.size(); i++) {
                            myReceiveList.add(mList.get(i).getCommodityName());
                        }
                        if (mList.get(position).isSelect() == true) {
                            Log.d("TrueTrue", "选择选择");
                            applyIds.add(mList.get(position).getCommodityId());
                            detailIds.add(mList.get(position).getApplyDetailId());
                            commpanyNames.add(mList.get(position).getCommodityName());
                            ids.add(mList.get(position).getApplyDetailId());
                            ToolList.removeDuplicateWithOrder(applyIds);
                            ToolList.removeDuplicateWithOrder(detailIds);
                            ToolList.removeDuplicateWithOrder(commpanyNames);
                            ToolList.removeDuplicateWithOrder(ids);
                            Log.d("commpanyNames", commpanyNames.toString());
                            Log.d("mListsize", mList.size() + "");
                            Log.d("applyIdssize", applyIds.size() + "");
                     /*       if (applyIds.size() == mNewList.get(parentPosition).getDetails().size()) {
                                mNewList.get(parentPosition).setSelect(true);
                                chuShiDingDanAdapter.notifyDataSetChanged();
                            } else {
                            }*/
                            if (applyIds.size() == mNewList.size()) {
                                mNewList.get(parentPosition).setSelect(true);
                                chuShiDingDanAdapter.notifyDataSetChanged();
                            } else {

                            }

                        } else {
                            mNewList.get(parentPosition).setSelect(false);
                            chuShiDingDanAdapter.notifyDataSetChanged();
                            if (applyIds.size() > 0) {
                                applyIds.remove(position);
                                detailIds.remove(position);
                                commpanyNames.remove(position);
                                ids.remove(position);
                            }
                            try {

                            } catch (Exception e) {

                            }

                            Log.d("取消勾选", "取消勾选");
                            /*if (applyIds.size() > 0) {
                                for (int i = 0; i < applyIds.size(); i++) {
                                    if (applyIds.get(i).contains(mList.get(i).getCommodityId())) {
                                        applyIds.remove(i);
                                    }
                                }
                            }
                            if (detailIds.size() > 0) {
                                for (int i = 0; i < detailIds.size(); i++) {
                                    if (detailIds.get(i).contains(mList.get(i).getApplyDetailId())) {
                                        detailIds.remove(i);
                                    }
                                }
                            }
                            if (commpanyNames.size() > 0) {
                                for (int i = 0; i < commpanyNames.size(); i++) {
                                    if (commpanyNames.get(i).contains(mList.get(i).getCommodityName())) {
                                        commpanyNames.remove(i);
                                    }
                                }
                            }
                            if (ids.size() > 0) {
                                for (int i = 0; i < ids.size(); i++) {
                                    if (ids.get(i).contains(mList.get(i).getApplyDetailId())) {
                                        ids.remove(i);
                                    }
                                }
                            }*/
                            Log.d("applyIds", applyIds.toString());
                            Log.d("detailIds", detailIds.toString());
                            Log.d("ids", ids.toString());
                            ToolList.removeDuplicateWithOrder(ids);
                            ToolList.removeDuplicateWithOrder(applyIds);
                            ToolList.removeDuplicateWithOrder(detailIds);
                            ToolList.removeDuplicateWithOrder(commpanyNames);
                            Log.d("commpanyNames", commpanyNames.toString());
                            Log.d("FalseFalse", "取消选择");
                        }


                        break;

                }
            }


        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        unbinder.unbind();
    }

    private int result_shouhuo = 100;

    @OnClick({R.id.recyclerview, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.recyclerview:
                break;
            case R.id.btn_submit:

                ToolList.removeDuplicateWithOrder(ids);
                String myApplyIds = MyStringUtils.returnStringBuffer(ids);
                Log.d("applyIdsapplyIds", ids.toString());
                Log.d("myApplyIds", myApplyIds);
                Log.d("cancelFlag", cancelFlag.toString());

                String str_send;
                if (flag == 1) {
                    str_send = "1";
                } else {
                    str_send = myApplyIds;
                }
                Log.d("supplierNameList", supplierNameList.toString());
                Log.d("dataBeanListdataBeanList", dataBeanList.size() + "");

                Log.d("supplierNameListsizisize", supplierNameList.size() + "");
                Log.d("idsidsids", ids.size() + "");

                ToolList.removeDuplicateWithOrder(supplierNameList);

                for (int i = 0; i < supplierNameList.size(); i++) {
                    if (supplierNameList.get(i).length() < 4 || supplierNameList.equals("") || supplierNameList.equals(" ")) {
                        supplierNameList.remove(i);
                    }
                }
                if (cancelFlag.toString().contains("1")) {
                    Toast.makeText(mContext, "请恢复订单", Toast.LENGTH_SHORT).show();
                } else if (supplierNameList.isEmpty()) {
                    Toast.makeText(mContext, "请选择供应商", Toast.LENGTH_SHORT).show();
                } else if (supplierNameList.size() == 0) {
                    Toast.makeText(mContext, "请选择供应商", Toast.LENGTH_SHORT).show();
                } else if (ids.size() == 0) {
                    Toast.makeText(mContext, "请选择商品", Toast.LENGTH_SHORT).show();
                } else if (ids.isEmpty()) {
                    Toast.makeText(mContext, "请选择商品", Toast.LENGTH_SHORT).show();
                } else {

                    Log.d("str_sendstr_send", str_send);
                    HttpResponse.createOrder(token, str_send, new StringCallback(getActivity()) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            BaseBean baseBean = new BaseBean();
                            baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                            if (baseBean.getCode()==0){
                                EventBus.getDefault().post(2);
                            }

                            Toast.makeText(mContext, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
//                            initData();
                            getData();
                            Log.d("CAIGOURENYUAN", s);
                        }
                    });
                }


                break;

        }
    }

    String resurtResurant;
    String reason;
    int flag = 0;
    String gongName;
    String position;
    String receivestr;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == result_shouhuo) {
            resurtResurant = data.getStringExtra("flag");
            gongName = data.getStringExtra("gongName");
            position = data.getStringExtra("position");
            Log.d("resurtResurantFlag", resurtResurant);

            Log.d("gongNamegongName", gongName);
            if (resurtResurant.equals("1")) {
                flag = 1;
//                receivestr = data.getStringExtra("idSend_receiver");
//                Log.d("receivestr", receivestr);
            } else {
//
                flag = 0;
            }
            if (dataBeanList.size() > 0) {
                dataBeanList.clear();
            } else {
            }
            getData();
//            Toast.makeText(getActivity(), resurtResurant + "", Toast.LENGTH_SHORT).show();
        } else if (resultCode == result_fangqi) {
            reason = data.getStringExtra("reason");
            Log.d("Caiagdouddkdk", reason);
            HttpResponse.doShoppingCartCancel(token, applyDetailId, reason, new StringCallback(getActivity()) {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    Log.d("CaiGouRenDaiList", s);
                    BaseBean baseBean = new BaseBean();
                    baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                    Toast.makeText(mContext, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                    ids.clear();
//                    initData();
                    if (dataBeanList.size() > 0) {
                        dataBeanList.clear();
                    } else {
                    }
                    getData();
                }
            });

        }
    }

    public void registerBroad() {
        intentFilter = new IntentFilter();
        intentFilter.addAction("CaiGouRenDaiListragment");
        myBroadcastReceiver = new MyBroadcastReceiver();
        //注册广播
        getActivity().registerReceiver(myBroadcastReceiver, intentFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(myBroadcastReceiver);
    }
    public void onEventMainThread(Integer a) {


    }
}